// scaup - Scala up!
// (c) 2008-2009, Normen Müller, normen.mueller@gmail.com  
// $Id: conversions.scala 33 2009-11-03 15:56:20Z normen.mueller $
package scaup.data

/**
 * @author <a href="mailto:normen.mueller@googlemail.com">Normen M&#xFC;ller</a>
 * @version 0.0.2 */
object Conversions {  
  /** Converts a <code>java.util.List</code> to a scala list. */
  implicit def javaList2scalaList[A](xs: java.util.List[A]): scala.List[A] = xs match {
    case NonEmpty(h,t) => h :: t
    case Empty(_)      => Nil
  }
  
  /** Converts a scala list to a <code>java.util.List</code>. */
  implicit def scalaList2javaList[A](xs: scala.List[A]): java.util.List[A] = {
    val l = new java.util.LinkedList[A]
    xs foreach (l.add(_))
    l
  }
  
  /** Provides a non-empty extractor for <code>java.util.List</code>. */
  object NonEmpty {
    /** An extractor that returns a pair of the first element of a list and the remainder of the list if the list
     *  is not empty, otherwise, no match. */
    def unapply[A](xs: java.util.List[A]): Option[(A, java.util.List[A])] =
      if(xs isEmpty)
        None
      else Some((xs.get(0),xs.subList(1, xs.size)))
  }
  
  /** Provides an empty extractor for <code>java.util.List</code>. */
  object Empty {
    /** An extractor that returns <code>Some</code> if the given list is empty, <code>None</code> (no match) otherwise. */  
    def unapply[A](xs: java.util.List[A]): Option[Unit] = if(xs isEmpty) Some(()) else None
  }
  
  /** Converts a <code>java.util.Iterator</code> to a scala iterator. */
  implicit def javaIterator2scalaIterator[A](i: java.util.Iterator[A]) = new Iterator[A] {
    def next = i.next
    def hasNext = i.hasNext
  }
  
  /** Converts a scala iterator to a <code>java.util.Iterator</code>. */
  implicit def scalaIterator2javaIterator[A](i: Iterator[A]): java.util.Iterator[A] = new java.util.Iterator[A] {
    def next = i.next
    def hasNext = i.hasNext
    def remove = throw new UnsupportedOperationException
  }
  
  /** Converts a <code>java.util.Enumeration</code> to a scala iterator. */
  implicit def javaEnumeration2scalaIterator[A](e: java.util.Enumeration[A]) = new Iterator[A] {
    def hasNext = e.hasMoreElements
    def next = e.nextElement
  }
  
  /** Converts an iterator to a <code>java.util.Enumeration</code>. */
  implicit def scalaIterator2javaEnumeration[A](i: Iterator[A]) = new java.util.Enumeration[A] {
    def hasMoreElements = i.hasNext
    def nextElement = i.next
  }  
}
